package Util;

import org.hibernate.HibernateError;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

import java.util.Map;

/**
 * Created by studio on 2017/3/1.
 */
public class HibernateUtil {

    private static SessionFactory sessionFactory;
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static String database = "hibernate";

    static{
        try{
            //读取配置文件
            Configuration configuration = new Configuration().configure();

            //创建服务注册对象
            StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();

            sessionFactory = configuration.buildSessionFactory();

        }catch (Throwable ex){
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory(Map db){
        if (sessionFactory == null){
            rebuildSessionFactory();
            return sessionFactory;
        }

        String url = sessionFactory.getProperties().get("connection.url").toString();
//        String driver = db.get("driver_class").equals("com.mysql.jdbc.Driver")?"jdbc":"";
        String type = db.get("db_type").toString();
        String IP = db.get("IP").toString();
        String port = db.get("port").toString();
        database = db.get("DBName").toString();

        if (url.indexOf(type) < url.indexOf(IP) &&
                url.indexOf(IP) < url.indexOf(port) &&
                url.indexOf(port) < url.indexOf(database)){
            return sessionFactory;
        }else{
            rebuildSessionFactory();
        }
        return sessionFactory;
    }

    public static Session getSession() throws HibernateError{
        Session session = threadLocal.get();
        if(session == null || !session.isOpen()){
            if(sessionFactory == null){
                rebuildSessionFactory();
            }
            session = sessionFactory.openSession();
            threadLocal.set(session);
        }
        return session;
    }

    public static void rebuildSessionFactory(){
        Configuration configuration = new Configuration();
        configuration.configure(database + ".cfg.xml");
        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    }

    public static void closeSession(){
        Session session = threadLocal.get();
        threadLocal.set(null);
        if(session != null){
            session.close();
        }
    }

    public static void shutdown(){
        sessionFactory.close();
    }

}
